package com.mf.all.utils;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * @Author: lmf
 * @Create: 2025/3/25 23:17
 * @module
 */
@Component
public class UtilMail {

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.tos}")
    private String tos;

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 发送邮件
     *
     * @param subject 主题
     * @param text    内容
     */
    public void sendEmail(String subject, String text) {
        // 构建MimeMessage对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // 给邮件指定信息
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setTo(tos.split(","));
            setInfo(subject, text, helper);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    /**
     * 发送邮件
     *
     * @param to      要发送的邮箱
     * @param subject 主题
     * @param text    内容
     * @throws MessagingException 邮件发送异常
     */

    public void sendEmail(String to, String subject, String text) throws MessagingException {
        // 构建MimeMessage对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // 给邮件指定信息
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setTo(to);
        setInfo(subject, text, helper);

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    private void setInfo(String subject, String text, MimeMessageHelper helper) throws MessagingException {
        helper.setFrom(from);
        helper.setSubject(subject);
        helper.setText(text);
    }

}
